package anjos.servlet;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import anjos.modelo.AnjoEvento;
import anjos.modelo.Crianca;
import anjos.modelo.Evento;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import anjos.rn.AnjoEventoRN;
import anjos.rn.AnjoRN;
import anjos.rn.EventoRN;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author AlanmLira
 */
public class servletConnection extends HttpServlet {

    String controlador = null;
    String resultado = "";
    AnjoEventoRN aeRN = new AnjoEventoRN();
    EventoRN eRN = new EventoRN();
    int x = 0;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //controlador = request.get
        x = 0;
        controlador = request.getParameter("controlador");
        //Junior se tu ler executa essa url e da uma olhada no erro que dá e vê se consegue resolver
        //--->http://localhost:8080/Anjos/servletConnection?controlador=login&eve=1&senha=123 
        //só tem que preencher a tabela evento_anjos no MySQL
        System.out.println("valor: " + controlador);

        switch (controlador) {
            case "login":
                int aux = Integer.parseInt(request.getParameter("eve"));
                AnjoEvento ae = aeRN.obterUsuario(eRN.obter(aux), request.getParameter("senha"));
                if (ae != null) {
                    response.getOutputStream().print("s");
                } else {
                    response.getOutputStream().print("n");
                }
                break;
            case "todosEventos":
                List<Evento> lEventios = new EventoRN().obterTodos();
                resultado = "[{";
                x = 0;
                for (Evento evento : lEventios) {
                    if (x != 0) {
                        resultado += ",{";
                    } else {
                        x++;
                    }
                    resultado += "\"idEvento\":\"" + evento.getId() + "\",\"nomeEvento\":\""
                            + evento.getNome() + "\",\"descricaoEvento\":\""
                            + evento.getDescricao() + "\",\"statusEvento\":\""
                            + evento.getStatus() + "\",\"senhaEvento\":\""
                            + evento.getSenha() + "\"}";

                }
                resultado += "]";
                resultado = resultado.replace("/", "\\/");
                //System.out.println("resultado  :" + resultado);
                response.getOutputStream().print(resultado);
                break;
            case "todosPerdidos":
                List<Crianca> lCrianca = new AnjoRN().obterTodosCrincasPerdidas();
                resultado = "[{";
                x = 0;
                for (Crianca crianca : lCrianca) {
                    if (x != 0) {
                        resultado += ",{";
                    } else {
                        x++;
                    }
                    resultado += "\"idCrianca\":\"" + crianca.getId() + "\",\"nomeCrianca\":\""
                            + crianca.getNome() + "\",\"nomeResponsavel\":\""
                            + crianca.getResponsavel().getNome() + "\"}";

                }
                resultado += "]";
                resultado = resultado.replace("/", "\\/");
                System.out.println("resultado  :" + resultado);
                response.getOutputStream().print(resultado);
                break;
            default:
                response.getOutputStream().print("Erro ao fazer a conexão com o servidor.");
        }



    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            int length = request.getContentLength();
            byte[] input = new byte[length];
            ServletInputStream sin = request.getInputStream();
            int c, count = 0;
            while ((c = sin.read(input, count, input.length - count)) != -1) {
                count += c;
            }
            sin.close();

            String recievedString = new String(input);
            response.setStatus(HttpServletResponse.SC_OK);
            OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());

            Integer doubledValue = Integer.parseInt(recievedString) * 2;

            writer.write(doubledValue.toString());
            writer.flush();
            writer.close();



        } catch (IOException e) {


            try {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().print(e.getMessage());
                response.getWriter().close();
            } catch (IOException ioe) {
            }
        }
    }
    /*
     protected void processRequest(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
     response.setContentType("text/html;charset=UTF-8");
     PrintWriter out = response.getWriter();
     try {
     // TODO output your page here. You may use following sample code. 
     out.println("<!DOCTYPE html>");
     out.println("<html>");
     out.println("<head>");
     out.println("<title>Servlet servletConnection</title>");
     out.println("</head>");
     out.println("<body>");
     out.println("<h1>Servlet servletConnection at " + request.getContextPath() + "</h1>");
     out.println("</body>");
     out.println("</html>");
     } finally {
     out.close();
     }
     }
     *//*
     // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
     /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     *//*
     @Override
     protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
     processRequest(request, response);
     }

     /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     *//*
     @Override
     protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
     String x = request.getParameter("x");
     System.out.println(" ----- X: " + x);
     processRequest(request, response);
     }

     /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     *//*
     @Override
     public String getServletInfo() {
     return "Short description";
     }// </editor-fold>
    
     */




}
